﻿using System;
using System.Web;
using System.Web.UI;
using BusinessLogic.BusinessRules;
using BusinessLogic.ClassFactory;
using Common;
using DataAccess;
using log4net;
using RichWebServiceDll;
using System.Web.UI.WebControls;
using ThreadControl;
using System.Data;
using Common.Xml;
using IssueCommon;

namespace RichECMS
{
    public partial class Login : Util.BasePage.BasePage
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Login));

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //扑捉是否正常登陆
                if (Request["ReturnUrl"] != null)
                {
                    log.DebugFormat("Page Response Error，Name：{0}", Request["ReturnUrl"].ToString());
                }
                InitDataBindwebsiteByUrl();
            }
            //初始化页面数据
            //InitData();
        }

        /// <summary>
        /// 输出网站
        /// </summary>
        private void InitDataBindwebsiteByUrl()
        {
            DropDownListWebName.Items.Clear();
            string strDomain = Request.Url.Host.ToLower();
            //绑定网站
            ListItem listitem = new ListItem();
            //listitem = new ListItem("--请选择网站后台--", "-1");
            //DropDownListWebName.Items.Add(listitem);
            using (WebSiteFactory objWebSiteFactory = new WebSiteFactory())
            {
                BusinessLogic.BusinessRules.WebSite objWebSite = objWebSiteFactory.NewInstance();
                //if (strDomain == "localhost" || strDomain.Contains("192.168.") || (strDomain.IndexOf("test") != -1 && strDomain.IndexOf("hnrich.net") != -1))
                //{
                objWebSite = objWebSiteFactory.CreatorBySql(" intWSState=" + (int)Utility.WebSiteState.Use);
                //}
                //else
                //{
                //    objWebSite = objWebSiteFactory.CreatorBySql(" intWSState=" + (int)Utility.WebSiteState.Use + " and chvWebUrl=" + strDomain);
                //    特例情况 暂时
                //    if (objWebSite != null)
                //    {
                //        objWebSite = objWebSiteFactory.CreatorBySql(" intWSState=" + (int)Utility.WebSiteState.Use);
                //    }
                //}

                if (objWebSite != null)
                {
                    for (int i = 0; i < objWebSite.Count; i++)
                    {
                        listitem = new ListItem(objWebSite.DataItem.chvName, objWebSite.DataItem.intWebSiteID.ToString());
                        DropDownListWebName.Items.Add(listitem);
                        objWebSite.SelectRow(i + 1);
                    }
                }
            }
        }

        private void InitData()
        {
            //是否是本地使用
            string strNowUrl = Request.Url.Host;

            if (strNowUrl.IndexOf("localhost") != -1 || strNowUrl.IndexOf("test") != -1 || strNowUrl.IndexOf("192.168.") != -1)
            {
            }
            else
            {
                //效验验证信息
                string strRedrict = "###";
                bool isRedrict = false;
                using (ServerVariableFactory objFactory = new ServerVariableFactory())
                {
                    ServerVariable objServerVariable = objFactory.Creator();
                    if (objServerVariable != null)
                    {
                        //是否放弃绑定
                        if (objServerVariable.DataItem.intIsDrop == (int)Utility.IsDrop.No)
                        {
                            //是否是试用版
                            if (objServerVariable.DataItem.intLsTryUse == (int)Utility.IsTryUse.Yes)
                            {
                                //每次登陆需要获取服务器变更信息
                                RichWSComputerInfo objRichWSComputerInfo = new RichWSComputerInfo(objServerVariable.DataItem.chvServerIp, strNowUrl, objServerVariable.DataItem.chvImpowerNo);

                                if (objRichWSComputerInfo.RequestResultState.Trim() != "success")
                                {
                                    Alert("服务器错误：" + objRichWSComputerInfo.RequestResultState + objRichWSComputerInfo.RequestResultMessage);
                                    CloseLogin();
                                }
                                else
                                {
                                    //更新本地信息
                                    objServerVariable.DataItem.dtmWebEnd = objRichWSComputerInfo.WebEndTime;
                                    objServerVariable.DataItem.intIsAllMoney = objRichWSComputerInfo.IsAllMoney;
                                    objServerVariable.DataItem.intIsDrop = objRichWSComputerInfo.IsDrop;
                                    objServerVariable.DataItem.intLsTryUse = objRichWSComputerInfo.IsTryUse;
                                    objServerVariable.Update();
                                }

                                //是否到期
                                if (DateTime.Now.CompareTo(objServerVariable.DataItem.dtmWebEnd) == 1)
                                {
                                    //过期
                                    Alert("您的试用版已经过期，请联系网站制作人员！");
                                    CloseLogin();
                                }
                                else
                                {
                                    Alert("您当前使用的CMS是试用版，到期时间为" + objServerVariable.DataItem.dtmWebEnd);
                                }
                            }
                            else
                            {
                                //正常使用--效验使用日期是否过期
                                if (DateTime.Now.CompareTo(objServerVariable.DataItem.dtmWebEnd) == 1)
                                {
                                    //过期
                                    Alert("您的使用日期已经到了，请联系网站相关客服人员！");
                                    CloseLogin();
                                    return;
                                }
                            }
                        }
                        else
                        {
                            //放弃绑定后只做域名效验
                        }
                    }
                    else
                    {
                        //没有注册信息，跳转到注册信息页面
                        strRedrict = "Regist.aspx";
                        isRedrict = true;
                    }
                }
                if (isRedrict == true)
                {
                    IsAndRedirect(strRedrict, false);
                }
            }
        }
        private void CloseLogin()
        {
            txtUserName.Text = "..::已过期::..";

            txtPsw.ReadOnly = true;
            txtUserName.ReadOnly = true;
            ibtnLogin.Visible = false;
        }
        protected void ibtnLogin_Click(object sender, ImageClickEventArgs e)
        {
            if (Session["CheckCode"] == null)
            {
                AlertAndRedirect("请使用正常的方式登录", "login.aspx", false);
                return;
            }
            else
            {
                if (txtValidtcode.Text != Session["CheckCode"].ToString())
                {
                    Alert("验证码不正确");
                    return;
                }
            }
            string strRedrict = "###";
            bool isRedrict = false;
            using (DBManager _DBManager = new DBManager())
            {
                _DBManager.BeginTransaction();
                try
                {
                    UserManageInfoFactory objFactory = new UserManageInfoFactory(_DBManager);
                    UserManageInfo objUserManageInfo = objFactory.NewInstance();
                    if (DropDownListWebName.SelectedIndex != -1)
                    {
                        objUserManageInfo = objFactory.CreatorBySql(string.Format(" chvLoginName ='{0}' and intWSID={1}", txtUserName.Text.Trim(), DropDownListWebName.SelectedValue));
                    }
                    else
                    {
                        if (txtUserName.Text.Trim().ToLower() == "sysadmin")
                        {
                            WebSiteFactory objWebSiteFactory = new WebSiteFactory(_DBManager);
                            WebSite objwebsitetemp = objWebSiteFactory.Creator();
                            if (objwebsitetemp == null)
                            {
                                System.Web.Security.FormsAuthentication.SetAuthCookie("Login", false);
                                State.LoginUser = new SessionUser();
                                State.LoginUser.LoginName = "FirstSysadmin";
                                State.LoginUser.ManagerCompetence = 0;
                                strRedrict = "ServerPages/MainWebSiteContaolPanel.aspx";
                                isRedrict = true;
                            }
                            else
                            {
                                Alert("没有此用户！");
                                log.DebugFormat("User Error，Name：{0}", txtUserName.Text.Trim());
                                return;
                            }
                        }
                        else
                        {
                            Alert("没有此用户！");
                            log.DebugFormat("User Error，Name：{0}", txtUserName.Text.Trim());
                            return;
                        }
                    }

                    if (objUserManageInfo != null)
                    {
                        if (objUserManageInfo.Count > 0)
                        {
                            if (objUserManageInfo.DataItem.chvLoginName.Trim() != txtUserName.Text.Trim())
                            {
                                Alert("用户名或者密码错误，请重新填写！");
                                return;
                            }
                            string strDBPsw = EncryptUtily.EncryptUtily.LoginDecrypt(ClearHTMLAndSQL(objUserManageInfo.DataItem.chvLoginPsw));
                            if (txtPsw.Text.Trim() != strDBPsw)
                            {
                                Alert("用户名或者密码错误，请重新填写！");
                                log.DebugFormat("User Error，Name：{0}", txtPsw.Text.Trim());
                                return;
                            }

                            System.Web.Security.FormsAuthentication.SetAuthCookie("Login", false);
                            SessionUser objSessionUser = new SessionUser();//储存

                            objSessionUser.LoginName = txtUserName.Text.Trim();
                            objSessionUser.Psw = strDBPsw;
                            objSessionUser.UserID = objUserManageInfo.DataItem.intUserID;
                            objSessionUser.EnableParentPath = false;
                            objSessionUser.EnableSectionID= false;
                            State.LoginUser = objSessionUser;

                            UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory(_DBManager);
                            UserWebRelation objUserWebRelation = objUserWebRelationFactory.CreatorBySql("chvLoginName='" + objSessionUser.LoginName + "' and intState=1 and intUserID=" + objUserManageInfo.DataItem.intUserID);
                            if (objUserWebRelation != null)
                            {
                                State.IsManager = true;
                                LoginLogFactory objLoginLogFactory = new LoginLogFactory(_DBManager);
                                //查询上次登录
                                LoginLog objLoginLog =
                                    objLoginLogFactory.CreatorBySql(
                                        string.Format(" chvLoginName='{0}' order by dtmLoginDatetime desc",
                                                      State.LoginUser.LoginName));
                                if (objLoginLog != null)
                                {
                                    State.LoginUser.DtmLastAccessTime = objLoginLog.DataItem.dtmLoginDatetime;
                                }
                                //插入此次登陆记录
                                objLoginLog = objLoginLogFactory.NewInstance();
                                objLoginLog.DataItem.chvLoginName = State.LoginUser.LoginName;
                                objLoginLog.DataItem.dtmLoginDatetime = DateTime.Now;
                                objLoginLog.DataItem.chvIp = Request.UserHostAddress;
                                objLoginLog.Insert();

                                if (objUserWebRelation.Count > 1)
                                {
                                    strRedrict = "ServerPages/MainWebSiteContaolPanel.aspx";
                                    isRedrict = true;
                                }
                                else
                                {
                                    //是否启用父路径
                                    XMLProcess objXMLProcess = new XMLProcess("Setting\\GlobalSet.config");
                                    string enableParentPath= objXMLProcess.ReadAttribute("/configuration/GlobalSet/ParentPath", "Enable");
                                    if (enableParentPath.Trim().ToLower() == "true")
                                    {
                                        State.LoginUser.EnableParentPath = true;
                                        //启用父路径情况下是否启用栏目ID
                                        string enableSectionID = objXMLProcess.ReadAttribute("/configuration/GlobalSet/ParentPath", "EnableSectionID");
                                        if (enableSectionID.Trim().ToLower() == "true")
                                        {
                                            State.LoginUser.EnableSectionID = true;
                                        }

                                        //是否启用短路径
                                        string enableShortPath = objXMLProcess.ReadAttribute("/configuration/GlobalSet/ShortPath", "Enable");
                                        if (enableShortPath.Trim().ToLower() == "true")
                                        {
                                            State.LoginUser.EnableShortPath = true;
                                        }
                                    }

                                    SystemVariableFactory objSystemVariableFactory = new SystemVariableFactory(_DBManager);
                                    SystemVariable objSystemVariable = objSystemVariableFactory.CreatorBySql("intWSID=" + objUserWebRelation.DataItem.intWSID);
                                    if (objSystemVariable != null)
                                    {
                                        string strRepleaceOld = "login.aspx".ToLower();

                                        string strwebpath = Server.MapPath(Request.Path).ToLower().Replace(strRepleaceOld, "");
                                        State.LoginUser.WebSiteID = objSystemVariable.DataItem.intWSID;
                                        //记录权限
                                        State.LoginUser.ManagerCompetence = objUserWebRelation.DataItem.intManager;

                                        DataTable tblTmp = objUserWebRelation.Data.Tables[0];
                                        DataRow row = tblTmp.Rows[0];
                                        State.LoginUser.Permissions = row["chvPermissions"] != DBNull.Value ? objUserWebRelation.DataItem.chvPermissions : "";
                                        State.LoginUser.PermissionsText = row["chvPermissionsText"] != DBNull.Value ? objUserWebRelation.DataItem.chvPermissionsText : "";
                                        State.LoginUser.StrName = row["chvUserName"] != DBNull.Value ? objUserWebRelation.DataItem.chvUserName : "";

                                        State.LoginUser.VartualPath = objSystemVariable.DataItem.chvIssuePath;
                                        State.LoginUser.Rootpath = strwebpath;
                                        State.LoginUser.IssuePath = strwebpath + (State.LoginUser.EnableParentPath?"":("news\\" + objSystemVariable.DataItem.chvIssuePath+"\\"));
                                        State.LoginUser.MiniPicPath = strwebpath + "Pcfiles\\" + objSystemVariable.DataItem.chvMiniPicPath;
                                        State.LoginUser.PicPath = strwebpath + "Pcfiles\\" + objSystemVariable.DataItem.chvPicPath;
                                        State.LoginUser.WebUrl = objSystemVariable.DataItem.chvWebUrl;
                                        State.LoginUser.TemplatePath = strwebpath + "TemplateFile\\" + objSystemVariable.DataItem.chvTemplatePath;

                                        //获取网站等级
                                        WebSiteFactory objWebSiteFactory = new WebSiteFactory();
                                        WebSite objWebSite = objWebSiteFactory.Creator(objUserWebRelation.DataItem.intWSID);
                                        if(objWebSite!=null)
                                        {
                                            State.LoginUser.WebSiteLevel = objWebSite.DataItem.IsintWebSiteLevelNull() ? 0 : objWebSite.DataItem.intWebSiteLevel;
                                        }
                                    }
                                    if (State.LoginUser.ManagerCompetence > (int)Utility.ManagerCompetence.Designer)
                                    {
                                        strRedrict = "ServerPages/Main.aspx?Wid=" + objUserWebRelation.DataItem.intWSID;
                                        isRedrict = true;
                                    }
                                    else
                                    {
                                        strRedrict = "ServerPages/MainWebSiteContaolPanel.aspx";
                                        isRedrict = true;
                                    }
                                }
                            }
                            else
                            {
                                Alert("您的账户不存在不或处于异常状态");
                            }
                        }
                    }
                    else
                    {
                        Alert("您的账户不存在不或处于异常状态");
                    }
                    _DBManager.Commit();
                }
                catch (Exception ex)
                {
                    _DBManager.Rollback();
                    _DBManager.Dispose();
                    Alert(ex.Message);
                    return;
                }
                finally
                {
                    _DBManager.Dispose();
                }
            }
            if (isRedrict == true)
            {
                IsAndRedirect(strRedrict, false);
            }
        }
    }
}